#include <func.h>

#define ERROR_CHECK(num, errno, str) {    \
        error(num, errno, str);           \
}

// 客户端
int main(void)
{
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == -1)
        error(1, errno, "socket");

    struct sockaddr_in addr;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "connect");

    printf("开始聊天\n");
    fd_set set;
    while(1)
    {
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(sock_fd, &set);
        if(select(sock_fd + 1, &set, NULL ,NULL ,NULL) == -1)
            error(1, errno, "select");
        char buf[128] = {0};

        if(FD_ISSET(STDIN_FILENO, &set))
        {
            int err = read(STDIN_FILENO, buf, 128);
            switch(err)
            {
            case -1:
                ERROR_CHECK(err, -1, "read");   break;
            case 0:
                printf("stdin 里面什么也没有\n");   break;
            default:
                if(send(sock_fd, buf, 128, 0))
                    error(1, errno, "send");
            }
        }

        if(FD_ISSET(sock_fd, &set))
        {
            ssize_t err = recv(sock_fd, buf, 128, 0);
            switch(err)
            {
            case -1:
                error(1, errno, "recv");    break;
            case 0:
                printf("已将您移除群聊，不要潜水\n");   break;
            default:
                printf("other: %s\n", buf); break;
            }
        }
    }

    close(sock_fd);
    return 0;
}

